<template>
  <kk-container
    pageBackground="#E3EFFA"
    :showLoading="showLoading"
    :refresherEnabled="false"
  >
    <image
      class="mainContainerBg"
      src="@/pagesA/static/images/login/login_bg.png"
    ></image>
    <view v-if="mode === 0" class="column-center mainContainer">
      <image class="logo" src="/static/images/common/logo.png"></image>
      <view class="logoTitle">欢迎登录库课云</view>
      <view class="loginForm">
        <view style="height: 24rpx"></view>
        <up-input
          class="loginForm-account input"
          style="margin-top: 24rpx"
          placeholder="请输入登录账号"
          border="none"
          type="number"
          number
          clearable
          :maxlength="11"
          v-model="account"
        ></up-input>
        <up-input
          v-if="loginMode === 0"
          class="loginForm-password input"
          placeholder="输入登录密码"
          :password="isShowPassword ? false : true"
          border="none"
          v-model="password"
          :maxlength="20"
          clearable
          ><template #suffix>
            <image
              class="passwordEyeImage"
              :src="passwordEyeImage"
              @click="isShowPassword = !isShowPassword"
            ></image> </template
        ></up-input>
        <up-input
          v-if="loginMode === 1"
          class="loginForm-password input"
          placeholder="请输入验证码"
          border="none"
          v-model="code"
          number
          clearable
          :maxlength="6"
          ><template #suffix>
            <view
              class="getCodeStyle"
              :style="{ opacity: account.length === 11 ? 1 : 0.5 }"
              @tap="getCode"
              >{{ tips }}</view
            >
          </template></up-input
        >
        <up-code
          v-if="loginMode === 1"
          :seconds="seconds"
          ref="uCodeRef"
          @change="codeChange"
        ></up-code>
        <view style="height: 24rpx"></view>
      </view>
      <view v-if="errMsg" class="errMsg">{{ errMsg }}</view>
      <view v-else class="errMsg" style="height: 32rpx"></view>
      <view
        class="loginBtn"
        :style="{ opacity: loginIsEnabled ? 1.0 : 0.5 }"
        @tap="loginClick"
        >立即登录</view
      >
      <!-- <aliyun-captcha
        class="hiddenChild"
        id="captcha-element"
        v-if="loadCaptcha"
        :props="pluginProps"
      /> -->
      <view class="loginMethod" @tap="loginMethodClick">{{ loginMethod }}</view>
      <view class="phoneAgree">
        <view class="phoneAgree-radioBg">
          <image
            mode="aspectFill"
            class="phoneAgree-radio"
            :class="{
              'phoneAgree-radioChecked': protocolSelected,
            }"
            :data-flag="protocolSelected"
            :src="phoneProtocolImage"
            @tap="radioChange"
          ></image>
        </view>
        <text class="phoneAgree-desc">已阅读并同意</text>
        <text class="phoneAgree-protocol" data-type="1" @tap="gotoPrivacy"
          >《用户注册协议》</text
        >
        <text class="phoneAgree-protocol" data-type="2" @tap="gotoPrivacy"
          >《隐私政策》</text
        >
      </view>
    </view>
    <!-- <tenantSelect v-else :list="tenantList" /> -->
  </kk-container>
</template>

<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, watch } from "vue";
import { computed } from "vue";
import kkToast from "@/utils/kkToast";
import {
  saveKKToken,
  saveUserLoginPhone,
  getOssToken,
  saveOssToken,
} from "@/utils/storageUtil";
import { btoa } from "js-base64";
import { useUserStore } from "@/store";

// import TenantSelect from "./tenantSelect.vue";

import * as KKLoginApi from "@/api/login";

const userStore = useUserStore();
const { requestUserInfo } = userStore;

const protocolSelected = ref(false);

const phoneProtocolImage = computed(() => {
  return protocolSelected.value
    ? "/static/images/common/icon-choice-checked.png"
    : "/static/images/common/icon-choice-default.png";
});

const passwordEyeImage = computed(() => {
  return isShowPassword.value
    ? "/static/images/login/login_eye_show.png"
    : "/static/images/login/login_eye_hidden.png";
});

const mode = ref(0); // 0 登录 1 选择租户
const loginMode = ref(0); // 0 账号密码登录 1 手机验证码登录
const errMsg = ref("");
const account = ref("");
const password = ref("");
const code = ref("");
const tips = ref("获取验证码");
const seconds = ref(60);
const uCodeRef = ref(null);
const isShowPassword = ref(false);
const loginIsEnabled = ref(false);
const showLoading = ref(false);
const codeIsSendSuccess = ref(false);

loginIsEnabled.value = true;

const loginMethod = computed(() => {
  return loginMode.value === 0 ? "验证码登录" : "账号密码登录";
});

const tenantList = ref([]);

const loginMethodClick = () => {
  if (loginMode.value === 0) {
    loginMode.value = 1;
  } else {
    loginMode.value = 0;
  }
  change();
};
const loginClick = () => {
  if (!loginIsEnabled.value) return;
  if (!inputInfoVerify()) return;
  // 0 账号密码登录 1 手机验证码登录
  if (loginMode.value === 0) {
    accountPasswordLogin();
    //账号密码登录
  } else if (loginMode.value === 1) {
    // 1 手机验证码登录
    verificationCodeLogin();
  }
};

const radioChange = (e: any) => {
  const { flag } = e.currentTarget.dataset;
  protocolSelected.value = !flag;
};

watch(account, (newValue, _) => {
  account.value = newValue;
  change();
});
watch(password, (newValue, _) => {
  password.value = newValue;
  change();
});

watch(code, (newValue, _) => {
  code.value = newValue;
  change();
});

const change = () => {
  errMsg.value = "";

  if (loginMode.value === 0) {
    if (
      account.value &&
      password.value &&
      account.value.length === 11 &&
      password.value.length >= 8 &&
      password.value.length <= 20
    ) {
      loginIsEnabled.value = true;
    } else {
      loginIsEnabled.value = false;
    }
  } else if (loginMode.value === 1) {
    if (
      account.value &&
      account.value.length === 11 &&
      codeIsSendSuccess.value &&
      code.value.length == 6
    ) {
      loginIsEnabled.value = true;
    } else {
      loginIsEnabled.value = false;
    }
  }
};

const codeChange = (text: string) => {
  console.log("验证码格式:", text);
  tips.value = text;
};

const regPhone = /^1[3-9][0-9]{9}$/;

const inputInfoVerify = (veriftProtocol = true) => {
  if (!regPhone.test(account.value) || account.value.length !== 11) {
    kkToast.showToast("手机号码格式不正确");
    return false;
  }
  if (!protocolSelected.value && veriftProtocol) {
    kkToast.showToast("请阅读并勾选服务协议");
    return false;
  }

  return true;
};

const getCode = async () => {
  if (!account.value || account.value.length !== 11) {
    return;
  }
  if (showLoading.value) return;
  if (!inputInfoVerify(false)) return;
  showLoading.value = true;
  const data = (await KKLoginApi.getVerificationCode(account.value).catch(
    (err) => {
      showLoading.value = false;
    }
  )) as any;

  if (data && Number(data.code) === 10000) {
    showLoading.value = false;
    uCodeRef.value.start();
    codeIsSendSuccess.value = true;
  }
};

const gotoPrivacy = (e: any) => {
  let title = "";
  let protocolUrl = "";
  const { type } = e.currentTarget.dataset;
  if (type === "1") {
    title = "用户注册协议";
    protocolUrl = "/pagesA/agreement/user";
  } else if (type === "2") {
    title = "隐私政策";
    protocolUrl = "/pagesA/agreement/privacy";
  }
  const url = encodeURIComponent(protocolUrl);
  uni.navigateTo({
    url: protocolUrl,
  });
};

// 账号密码登录
const accountPasswordLogin = async () => {
  if (showLoading.value) return;
  const passwordEnCode = btoa(password.value);
  showLoading.value = true;
  const data = (await KKLoginApi.login({
    username: account.value,
    password: passwordEnCode,
  }).catch((err) => {
    showLoading.value = false;
  })) as any;
  showLoading.value = false;
  if (data && data.data) {
    handleLoginComplete(data.data);
  }
};

// 验证码登录
const verificationCodeLogin = async () => {
  if (showLoading.value) return;
  showLoading.value = true;
  const data = (await KKLoginApi.verificationLogin({
    mobile: account.value,
    code: code.value,
  }).catch((err) => {
    showLoading.value = false;
  })) as any;
  showLoading.value = false;
  if (data && data.data) {
    handleLoginComplete(data.data);
  }
};

// 登录之后
const handleLoginComplete = async (data: any) => {
  if (data && data.token) {
    saveKKToken(data.token);
    saveUserLoginPhone(account.value);
  }
  await requestUserInfo().catch(() => {});
  uni.reLaunch({
    url: "/pages/index/index",
  });
};

onLoad((options) => {
  const ossToken = getOssToken();
  uni.clearStorageSync();
  if (ossToken) {
    saveOssToken(ossToken);
  }
  change();
});

// 获取验证码登录
</script>

<style lang="scss" scoped>
.mainContainerBg {
  position: absolute;
  width: 100vw;
  height: 100vh;
}
.mainContainer {
  position: relative;
  width: 100vw;
  height: 100vh;
  .logo {
    margin-top: 225rpx;
    width: 221rpx;
    height: 161rpx;
  }
  .logoTitle {
    padding-top: 24rpx;
    font-weight: 600;
    font-size: 40rpx;
    color: #111111;
    line-height: 32rpx;
  }
  .loginMethod {
    margin-top: 48rpx;
    font-size: 32rpx;
    color: #666666;
    line-height: 32rpx;
  }
}
.loginForm {
  margin-top: 96rpx;
  margin-left: 48rpx;
  margin-right: 48rpx;
  width: calc(100vw - 96rpx);
  height: 272rpx;
  background: #ffffff;
  border-radius: 17rpx;
  .input {
    height: 112rpx;
    margin-left: 40rpx;
    margin-right: 40rpx;
  }
}
:deep(.u-input) {
  height: 112rpx;
  margin-left: 40rpx;
  margin-right: 40rpx;
}
.getCodeStyle {
  font-size: 32rpx;
  color: #386ef5;
  line-height: 32rpx;
  margin-right: 8rpx;
}
.errMsg {
  font-weight: 400;
  font-size: 28rpx;
  color: #666666;
  line-height: 32rpx;
  padding-top: 48rpx;
}
.loginBtn {
  margin-top: 48rpx;
  height: 98rpx;
  width: calc(100vw - 96rpx);
  background: #386ef5;
  border-radius: 56rpx;
  font-weight: 500;
  font-size: 32rpx;
  color: #ffffff;
  line-height: 98rpx;
  text-align: center;
}
.phoneAgree {
  margin-top: auto;
  margin-bottom: 96rpx;
  display: flex;
  flex-direction: row;

  &-radio {
    margin-top: -2rpx;
    width: 48rpx;
    height: 48rpx;
    margin-left: 0rpx;
    margin-right: 0rpx;
  }

  &-radioChecked {
    margin-top: -2rpx;
    margin-left: 0rpx;
    margin-right: 0rpx;
    width: 48rpx;
    height: 48rpx;
  }

  &-radioBg {
    margin-top: -8rpx;
    width: 48rpx;
    height: 48rpx;
  }

  &-desc {
    height: 32rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 32rpx;
    color: #666666;
  }

  &-protocol {
    height: 32rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 32rpx;
    color: #386ef5;
  }
}
.hiddenChild {
  width: 0;
  height: 0;
  border: none;
  padding: 0;
  margin: 0;
  overflow: hidden;
}
.passwordEyeImage {
  margin-top: 10rpx;
  width: 36rpx;
  height: 36rpx;
}
</style>
